package com.example.lxq.retrofit_rxjavatest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 作者： lxq on 2017/4/28 16:15
 * 邮箱： 842202389@qq.com
 * 用途：
 */

public class DownloadSubscribe implements ObservableOnSubscribe<DownloadInfo> {
    private DownloadInfo downloadInfo;
    private OkHttpClient client;

    public DownloadSubscribe(DownloadInfo downloadInfo, OkHttpClient client) {
        this.downloadInfo = downloadInfo;
        this.client = client;
    }

    @Override
    public void subscribe(ObservableEmitter<DownloadInfo> e) throws Exception {
        final String fileurl = downloadInfo.getUrl();
        final long startLength = downloadInfo.getProgress();
        long totalLength = downloadInfo.getTotal();
        e.onNext(downloadInfo);

        final Request request = new Request.Builder().url(fileurl).addHeader("Range", "bytes=" + startLength + "-" + totalLength).build();
        Response response = client.newCall(request).execute();


        if (response != null && response.isSuccessful()) {
            InputStream io = response.body().byteStream();

            File file = new File(fileurl);
            FileOutputStream outputStream = new FileOutputStream(file, true);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = io.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
                e.onNext(downloadInfo);
            }
            outputStream.flush();
            io.close();
            outputStream.close();
        }

        e.onComplete();
    }
}
